package com.xlh.openai.handler;

import com.xlh.openai.builder.TextBuilder;
import com.xlh.openai.service.AIService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    private AIService aIService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    @Lazy
    private WxMpService wxMpService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        String answer = "";
        if(wxMessage.getMsgType().equals("text")){

            Thread conversationThread = new Thread(() -> {
                // 创建线程池
                String aiMessage = aIService.chat(wxMessage.getContent(), wxMessage.getFromUser());
                try {
                    // 获取一个大概值
                    List<String> messageChunk = listSubMessage(aiMessage);
                    for (int i = 0; i < messageChunk.size(); i++) {
                        WxMpKefuMessage message = WxMpKefuMessage
                                .TEXT()
                                .toUser(wxMessage.getFromUser())
                                .content(messageChunk.get(i))
                                .build();
                        wxMpService.getKefuService().sendKefuMessage(message);
                    }

                } catch (WxErrorException e) {
                    logger.error("回复客服消息失败！", e);
                }
            });
            threadPoolTaskExecutor.execute(conversationThread);
        } else{
            answer = "小码还不支持 除文本以外的其他消息类型！";
            return new TextBuilder().build(answer, wxMessage, weixinService);
        }
        return new TextBuilder().build("努力思考中...", wxMessage, weixinService);
    }

    /**
     * 将字符串切成1000个字符一份
     * @param str
     * @return
     */
    private static List<String> listSubMessage(String str){

        List<String> chunks = new ArrayList<>();
        int offer = 0;
        int maxSize = 500;
        while(offer < str.length()){
            if(offer + maxSize < str.length()){
                chunks.add(str.substring(offer, offer + maxSize));
            }else{
                chunks.add(str.substring(offer, str.length()));
            }
            offer += maxSize;
        }
        System.out.println(chunks);
        return chunks;
    }



}
